package com.bbcare.followup.plat.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.OSSClientUtil;
import com.bbcare.comm.PropertiesUtils;
import com.bbcare.comm.SeqUtil;
import com.bbcare.followup.plat.entity.ContentTemplVersion;
import com.bbcare.followup.plat.entity.FollowQueue;
import com.bbcare.followup.plat.entity.FollowQueueAuthority;
import com.bbcare.followup.plat.entity.FollowScheme;
import com.bbcare.followup.plat.entity.FollowSchemeVersion;
import com.bbcare.followup.plat.entity.FollowTask;
import com.bbcare.followup.plat.entity.FollowTaskContent;
import com.bbcare.followup.plat.entity.PatientQueueScheme;
import com.bbcare.followup.plat.service.IFollowQueueService;
import com.bbcare.followup.plat.store.ibatis.IConfCacheDAO;
import com.bbcare.followup.plat.store.ibatis.IContentTemplDAO;
import com.bbcare.followup.plat.store.ibatis.IFollowQueueAuthorityDAO;
import com.bbcare.followup.plat.store.ibatis.IFollowQueueDAO;
import com.bbcare.followup.plat.store.ibatis.IFollowSchemeDAO;
import com.bbcare.followup.plat.store.ibatis.IFollowTaskContentDAO;
import com.bbcare.followup.plat.store.ibatis.IFollowTaskDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientQueueSchemeDAO;

/*
 * @name:         队列信息服务类实现
 * @author:       DemonLee
 * @createTime:   2017.4.12
 * @description:  队列基本信息等
 * @modify:
 *
 */
@Service
public class FollowQueueService implements IFollowQueueService {
    private final Log logger = LogFactory.getLog(FollowQueueService.class);

    @Autowired
    private IFollowQueueDAO queueDao;

    @Autowired
    private IPatientQueueSchemeDAO patientQueueSchemeDao;

    @Autowired
    private IFollowQueueAuthorityDAO followQueueAuthorityDao;

    @Autowired
    private IFollowSchemeDAO schemeDao;

    @Autowired
    private IFollowTaskDAO taskDao;

    @Autowired
    private IFollowTaskContentDAO taskContentDao;

    @Autowired
    private IContentTemplDAO contentTemplDao;

    @Autowired
    private IConfCacheDAO IConfCacheDAO;


    public List<PatientQueueScheme> getPatientListByQueueId(Map<String, Object> paramMap) throws Exception {
        // 正常状态的患者
        paramMap.put("userStatus", Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
        return patientQueueSchemeDao.selectPatientByCondition(paramMap);
    }

    // 队列信息List查询接口实现
    public HashMap<String, Object> getQueueList(Map<String, Object> inputMap) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>(inputMap);
        String showFlag = String.valueOf(paramMap.get("showFlag"));
        // 默认查询正常状态下的队列
        if (null == paramMap.get("QUEUE_STATUS")) {
            paramMap.put("queueStatus", Constants.QUEUE_STATUS_NOMAL);
        } else {
            paramMap.put("queueStatus", paramMap.get("QUEUE_STATUS"));
        }
        int total = queueDao.countByAuthorid(paramMap);
        List<FollowQueue> fqList = new ArrayList<FollowQueue>();
        if (0 != total) {
        	 List<Map<String,Object>> lists =  IConfCacheDAO.selectAuthorId(paramMap);
         	if(lists!=null && lists.size()>0 && !"0".equals(showFlag)) {
         		fqList = queueDao.selectQueueByAuthority(paramMap);
         	}else {
         		fqList = queueDao.selectByAuthority(paramMap);
             }
        }

        String createTime = "";
        float percent = 0l;
        for (int i = 0; i < fqList.size(); i++) {
            int currNum = fqList.get(i).getCurrNum();
            int targetNum = fqList.get(i).getTargetNum();
            if (targetNum > 0) {
                percent = ((float) currNum / targetNum) * 100;

            }
            createTime = DateUtil.getTimeStampDay(fqList.get(i).getCreateTime());
            fqList.get(i).setPerCent(percent);
            fqList.get(i).setCreateTime(createTime);
        }
        //根据authorId -> jmszxyy13doc012查询此用户拥有哪些队列的权限
        String authorId = (String) inputMap.get("authorId");
        if (ObjectUtil.isNotEmpty(fqList)){
            List<String> queueIds = this.followQueueAuthorityDao.getDuiLieByAuthorId(authorId);
            fqList = fqList.stream().filter(item -> {
                if (queueIds.contains(item.getId())){
                    return true;
                }else {
                    return false;
                }
            }).collect(Collectors.toList());
        }
        HashMap<String, Object> fqMap = new HashMap<String, Object>();
        //fqMap.put("rows", fqList);
        //fqMap.put("total", total);
        fqMap.put("rows", fqList);
        fqMap.put("total", fqList.size());

        return fqMap;
    }

    @SuppressWarnings("unchecked")
	@Override
    @Transactional
    public String queueModify(Map<String,Object> queueMap) throws Exception {
    	FollowQueue queue =  (FollowQueue)queueMap.get("followQueue");
    	String authorId = (String)queueMap.get("authorId");
        // queueDao.saveQueueInfo(pt);
        if (StringUtils.isEmpty(queue.getId())) {
            String queueId = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_QUEUEID);
            String sysdate = DateUtil.getSysDateA();

            // String queueIcon = queue.getQueueIcon();
            queue.setId(queueId);
            queue.setCreateTime(sysdate);
            queue.setQueueStatus(Constants.QUEUE_STATUS_NOMAL);
            queue.setQueueType(Constants.QUEUE_TYPE_TENANT);
            if(queue.getTargetNum() == null){
            	queue.setTargetNum(-1); //无上限
            }
            // 新增需生成二维码并上传到服务器
            // queue.setQrCode("");
            if (StringUtils.isEmpty(queue.getQueueIcon())) {
                queue.setQueueIcon(PropertiesUtils.getProperty("defaultqueueLogo"));// 设置默认队列logo
            }

            String content = PropertiesUtils.getProperty("defaultQueueUrl");// 二维码跳转url
            content = content.replaceAll("QUEUE_ID", queueId);

            String qrcode = OSSClientUtil.uploadLogoQrCode(content, queue.getQueueIcon(),
                    PropertiesUtils.getProperty("queueQrcode"), "png");
            queue.setQrCode(qrcode);

            // 新增加时默认为管理员权限
            FollowQueueAuthority relation = new FollowQueueAuthority();
            relation.setId(SeqUtil.getSeqNo());
            relation.setQueueId(queueId);
            relation.setDoctorId(authorId);
            relation.setCreateTime(sysdate);
            relation.setCreateAuthor(authorId);
            relation.setRole(Constants.QUEUE_DOCTOR_ADMIN);
            relation.setStatus(Constants.TABLE_RECORD_STATUS_NOMAL);
            queueDao.saveQueue(queue);

            List<FollowQueueAuthority> list = new ArrayList<FollowQueueAuthority>();
            list.add(relation);
            followQueueAuthorityDao.saveQueueRole(list);
        } else {
            // queue.getId();
        	//根据队列现有状态判断 哪些可以修改
        	Map<String,Object> map = new HashMap<String,Object>();
        	map.put("id",queue.getId());
        	List<FollowQueue> list = queueDao.selectById(map);
        	if(CollectionUtils.isEmpty(list)){

        	}else{
        		//限制修改条件
        		queue.setUpdateTime(DateUtil.getSysDateA());
                queueDao.updateQueueInfo(queue);

                Map<String,Object> mapDelete = new HashMap<String, Object>();
                mapDelete.put("queueId",queue.getId());
                mapDelete.put("roleAdmin",Constants.QUEUE_DOCTOR_ADMIN);
                mapDelete.put("status", Constants.TABLE_RECORD_STATUS_INVALID);
                // 删除之前的关系数据
                followQueueAuthorityDao.deleteQueueAuthoritys(mapDelete); //管理员不能修改和删除
        	}
        }

        List<FollowQueueAuthority> authoritys = null;
    	if(null != queueMap.get("queueAuthoritys")){
    		authoritys = (List<FollowQueueAuthority>)queueMap.get("queueAuthoritys");
    		 // 设置创建人
            String sysdate = DateUtil.getSysDateA();
            for (int i = 0; i < authoritys.size(); i++) {
            	if(authorId.equals(authoritys.get(i).getDoctorId())){
            		continue; //管理员 不需要处理 已经默认添加
            	}
                authoritys.get(i).setCreateTime(sysdate);
                authoritys.get(i).setId(SeqUtil.getSeqNo());
                authoritys.get(i).setQueueId(queue.getId());
                authoritys.get(i).setCreateAuthor(authorId);
                authoritys.get(i).setStatus(Constants.TABLE_RECORD_STATUS_NOMAL);
            }

            // 批量增加
            followQueueAuthorityDao.saveQueueRole(authoritys);
    	}

        return queue.getId();
    }

    @Override
    public int getQueueCount(Map<String, Object> paramMap) throws Exception {
    	paramMap.put("status", Constants.TABLE_RECORD_STATUS_NOMAL);
        int i = queueDao.countByAuthorid(paramMap);
        return i;
    }

    @Override
    @Transactional
    public int QueueDeleteById(Map<String, Object> paramMap) throws Exception {
        paramMap.put("queueStatus", Constants.QUEUE_STATUS_DELETE);
        int i = queueDao.deleteQueues(paramMap);

        // 删除队列的同时 删掉队列相关的管理信息
        paramMap.put("status", Constants.TABLE_RECORD_STATUS_INVALID);
        followQueueAuthorityDao.deleteQueueAuthoritys(paramMap);
        return i;
    }

    @Override
    public int QueueAuthoritryDeleteByIds(List<String> list) throws Exception {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    @Transactional
    public int queueAuthorityModify(List<FollowQueueAuthority> list) throws Exception {
        // 先删除 再增加
        Map<String, Object> queueMap = new HashMap<String, Object>();
        queueMap.put("queueId", list.get(0).getQueueId());
        queueMap.put("status", Constants.TABLE_RECORD_STATUS_INVALID);
        // 删除之前的关系数据
        followQueueAuthorityDao.deleteQueueAuthoritys(queueMap);
        // 批量增加
        followQueueAuthorityDao.saveQueueRole(list);

        return 0;
    }

    @Override
    public List<Map<String, Object>> queuemanagerDoctors(Map<String, Object> paramMap) throws Exception {
    	paramMap.put("status", Constants.TABLE_RECORD_STATUS_NOMAL);
        return followQueueAuthorityDao.queueManagerDoctors(paramMap);
    }

    @Override
    public FollowQueue getQueueDetailByQueueId(Map<String, Object> paramMap) throws Exception {
        List<FollowQueue> list = queueDao.selectById(paramMap);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        FollowQueue queue = list.get(0);
        String createTime = DateUtil.getTimeStampDay(queue.getCreateTime());
        queue.setCreateTime(createTime);
        return queue;
    }

    @Override
    @Transactional
    public void queueAdminTransfer(Map<String, Object> paramMap) throws Exception {
        // 先删除当前医生和队列的角色关系 再新增
        String sysdate = DateUtil.getSysDateA();

        String queueId = String.valueOf(paramMap.get("queueId"));
        String toDoctorId = String.valueOf(paramMap.get("toDoctorId"));
//        String fromDoctorId = String.valueOf(paramMap.get("authorId"));
        String authorId = String.valueOf(paramMap.get("authorId"));

        Map<String, Object> deleteDoctorTo = new HashMap<String, Object>();
        deleteDoctorTo.put("queueId", queueId);
        deleteDoctorTo.put("doctorId", toDoctorId);
        deleteDoctorTo.put("status", Constants.TABLE_RECORD_STATUS_NOMAL);
        /*
         * List<Map<String,Object>> result =
         * followQueueAuthorityDao.queueManagerDoctors(deleteDoctorTo);
         * if(CollectionUtils.isEmpty(result)){ throw new
         * AppException("10203004", "被转让的医生不在队列团队中"); }
         */

        Map<String, Object> deleteDoctorFrom = new HashMap<String, Object>();
        deleteDoctorFrom.put("queueId", queueId);
        deleteDoctorFrom.put("doctorId", authorId);
        deleteDoctorFrom.put("status", Constants.TABLE_RECORD_STATUS_NOMAL);
        FollowQueueAuthority fromDoctor = followQueueAuthorityDao.selectQueueDoctor(deleteDoctorFrom);
        if (null == fromDoctor || !Constants.QUEUE_DOCTOR_ADMIN.equals(fromDoctor.getRole())) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_MANAGERDOCTOR,
                    "当前医生不是队列管理员，不能进行转移管理员操作");
        }

        List<String> deleteAuthoritys = new ArrayList<String>();
        deleteAuthoritys.add(toDoctorId);
        deleteAuthoritys.add(authorId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("queueId", queueId);
        map.put("doctorIds", deleteAuthoritys);
        map.put("status", Constants.TABLE_RECORD_STATUS_INVALID);
        followQueueAuthorityDao.deleteQueueAuthoritys(map);
        // followQueueAuthorityDao.deleteQueueAuthoritys(deleteDoctorFrom);

        // 插入新的关系
        List<FollowQueueAuthority> list = new ArrayList<FollowQueueAuthority>();

        FollowQueueAuthority authority = new FollowQueueAuthority();
        authority.setCreateAuthor(authorId);
        authority.setId(SeqUtil.getSeqNo());
        authority.setDoctorId(authorId);
        authority.setCreateTime(sysdate);
        authority.setQueueId(queueId);
        authority.setStatus(Constants.TABLE_RECORD_STATUS_NOMAL);
        authority.setRole(Constants.QUEUE_DOCTOR_COMMON);
        list.add(authority);

        FollowQueueAuthority toAuthority = new FollowQueueAuthority();
        toAuthority.setCreateAuthor(authorId);
        toAuthority.setId(SeqUtil.getSeqNo());
        toAuthority.setCreateTime(sysdate);
        toAuthority.setQueueId(queueId);
        toAuthority.setDoctorId(toDoctorId);
        toAuthority.setRole(Constants.QUEUE_DOCTOR_ADMIN);
        toAuthority.setStatus(Constants.TABLE_RECORD_STATUS_NOMAL);
        list.add(toAuthority);
        followQueueAuthorityDao.saveQueueRole(list);

    }

    @Override
    public List<Map<String, Object>> queueDoctorsQuery(Map<String, Object> paramMap) throws Exception {
    	paramMap.put("status", Constants.TABLE_RECORD_STATUS_NOMAL);
        return followQueueAuthorityDao.selectDoctorAndQueueRole(paramMap);
    }

    // 队列主页统计信息接口实现
    public Map<String, Object> qryQueueHomeStatistics(Map<String, Object> paramMap) throws Exception {
        // HashMap<String, Object> argMap = new HashMap<String,
        // Object>(paramMap);

        Map<String, Object> retMap = new HashMap<String, Object>();
        // 后续使用redis缓存，这里先简单写死处理
        retMap.put("dayActiveNum", 100);// 今日活跃
        retMap.put("weekActiveNum", 1000);// 周活跃
        retMap.put("dayFileNum", 20);// 今日建档
        retMap.put("dayOutpatientNum", 10);// 今日门诊
        retMap.put("allPatientNum", 2000);// 全部患者

        return retMap;
    }

    @Override
    public List<Map<String, Object>> qryTrenddataStatistics(Map<String, Object> paramMap) throws Exception {

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        String dateType = (String) paramMap.get("dateType");
        String busiType = (String) paramMap.get("busiType");
        Random random = new Random();

        // 1患者总数2随访上传3评估上传4监测上传5新增患者6活跃患者 //先写死。。。
        switch (busiType) {
        case "1":
            switch (dateType) {
            case "1":
                for (int i = 1; i < 8; i++) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("date", "4-" + i);
                    map.put("number", 10 + (random.nextInt(100 * i)));
                    list.add(map);
                }
                break;
            case "3":
                for (int i = 1; i < 7; i++) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("date", 4 + i + "月");
                    map.put("number", 10 + (random.nextInt(1000 * i)));
                    list.add(map);
                }
                break;
            default:
                break;
            }
            break;
        case "2":
            switch (dateType) {
            case "1":
                for (int i = 1; i < 8; i++) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("date", "4-" + i + "");
                    map.put("number", 10 + (random.nextInt(20 * i)));
                    list.add(map);
                }
                break;
            case "3":
                for (int i = 1; i < 7; i++) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("date", 4 + i + "月");
                    map.put("number", 10 + (random.nextInt(200 * i)));
                    list.add(map);
                }
                break;
            default:
                break;
            }
            break;
        case "3":
            switch (dateType) {
            case "1":
                for (int i = 1; i < 8; i++) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("date", "4-" + i + "");
                    map.put("number", 10 + (random.nextInt(20 * i)));
                    list.add(map);
                }
                break;
            case "3":
                for (int i = 1; i < 7; i++) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("date", 4 + i + "月");
                    map.put("number", 10 + (random.nextInt(200 * i)));
                    list.add(map);
                }
                break;
            default:
                break;
            }
            break;
        case "4":
            switch (dateType) {
            case "1":
                for (int i = 1; i < 8; i++) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("date", "4-" + i + "");
                    map.put("number", 10 + (random.nextInt(20 * i)));
                    list.add(map);
                }
                break;
            case "3":
                for (int i = 1; i < 7; i++) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("date", 4 + i + "月");
                    map.put("number", 10 + (random.nextInt(200 * i)));
                    list.add(map);
                }
                break;
            default:
                break;
            }
            break;
        case "5":
            switch (dateType) {
            case "1":
                for (int i = 1; i < 8; i++) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("number", "4-" + i + "");
                    map.put("date", 10 + (random.nextInt(20 * i)) + i);
                    list.add(map);
                }
                break;
            case "3":
                for (int i = 1; i < 7; i++) {
                    Map<String, Object> map = new HashMap<String, Object>();

                    map.put("number", 4 + i + "月");
                    map.put("date", 10 + (random.nextInt(300 * i)) + i);
                    list.add(map);
                }
                break;
            default:
                break;
            }
            break;
        case "6":
            switch (dateType) {
            case "1":
                for (int i = 1; i < 8; i++) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("number", "4-" + i + "");
                    map.put("date", 10 + (random.nextInt(30 * i)) + i);
                    list.add(map);
                }
                break;
            case "3":
                for (int i = 1; i < 7; i++) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("number", 4 + i + "月");
                    map.put("date", 10 + (random.nextInt(200 * i)) + i);
                    list.add(map);
                }
                break;
            default:
                break;
            }
            break;
        default:
            break;
        }
        return list;
    }

    @Override
    public Map<String, Object> getPregnancyStatistics(Map<String, Object> paramMap) throws Exception {
        Map<String, Object> retMap = new HashMap<String, Object>();
        // 后续使用redis缓存，这里先简单写死处理
        retMap.put("timePeriodFour", 20);
        retMap.put("timePeriodOne", 50);
        retMap.put("timePeriodThree", 60);
        retMap.put("timePeriodTwo", 80);

        return retMap;
    }

    @Override
    public Map<String, Object> getPatientResourceStatistics(Map<String, Object> paramMap) throws Exception {
        Map<String, Object> retMap = new HashMap<String, Object>();
        // 后续使用redis缓存，这里先简单写死处理
        retMap.put("manualNum", 30);
        retMap.put("scanCodeNum", 80);
        return retMap;
    }

	/**
	 * paramMap 必须传入 authorId、tenantId
	 */
	@Override
	public List<String> getQueueArrByAuthority(Map<String, Object> paramMap)
			throws Exception {
		Map<String, Object> qryQueueMap = new HashMap<String, Object>();
        qryQueueMap.put("authorId", paramMap.get("authorId"));
        qryQueueMap.put("queueStatus", Constants.QUEUE_STATUS_NOMAL);// 队列状态正常
        qryQueueMap.put("tenantId", paramMap.get("tenantId"));
        qryQueueMap.put("queueTypePrivate", Constants.QUEUE_TYPE_PRIVATE);
        qryQueueMap.put("queueTypeTenant", Constants.QUEUE_TYPE_TENANT);
        qryQueueMap.put("queueTypePublic", Constants.QUEUE_TYPE_PUBLIC);
        List<FollowQueue> fqList = null;
        List<Map<String,Object>> lists =  IConfCacheDAO.selectAuthorId(qryQueueMap);
    	if(lists!=null && lists.size()>0) {
    		fqList = queueDao.selectQueueIdByparentId(qryQueueMap);
    	}else {
    		fqList = queueDao.selectQueueIdByAuthority(qryQueueMap);
    	}
        List<String> queueIdArray = new ArrayList<String>();
        if (null != fqList && 0 != fqList.size()) {
            // 根据当前登录账号获取，其可以查看的队列id（权限处理比较复杂，这里先简化）
            int fqt = 0;
            for (; fqt < fqList.size(); fqt++) {
                FollowQueue fqVo = fqList.get(fqt);
                // 后续sql中用in条件处理（这里先不考虑返回结果超过1000个）
                queueIdArray.add(fqVo.getId());
            }
        }
		return queueIdArray;
	}



    // 患者添加某个队列的建档问卷查询接口实现
    public HashMap<String, Object> qryQueueSchemePatientAddContent(Map<String, Object> paramMap) throws Exception {
        HashMap<String, Object> argMap = new HashMap<String, Object>(paramMap);
        HashMap<String, Object> retOutMap = new HashMap<String, Object>();

        String schemeId = (String) argMap.get("schemeId");
        // String queueId = (String) argMap.get("queueId");
        // 校验方案是否存在
        Map<String, Object> qrySchemeMap = new HashMap<String, Object>();
        qrySchemeMap.put("id", schemeId);
        List<FollowScheme> fsList = schemeDao.selectById(qrySchemeMap);
        if (null == fsList || 0 == fsList.size()) {
            throw (
                    new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_SCHEME_NOT_EXIST, "方案不存在!"));
        }
        FollowScheme fshVo = fsList.get(0);
        Map<String, Object> qrySchemeVerMap = new HashMap<String, Object>();
        qrySchemeVerMap.put("schemeId", schemeId);
        qrySchemeVerMap.put("schemeVersion", fshVo.getNewVersion());
        List<FollowSchemeVersion> fsvList = schemeDao.selectBySchemeIdAndVersion(qrySchemeVerMap);
        if (null == fsvList || 0 == fsvList.size()) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_SCHEMEVERSION_NOT_EXIST, "方案版本记录不存在!"));
        }
        FollowSchemeVersion fsvVo = fsvList.get(0);
        Map<String, Object> taskMap = new HashMap<String, Object>();
        taskMap.put("schemeVersionid", fsvVo.getId());
        taskMap.put("taskType", Constants.TASK_TYPE_SCHEME_SCHEDULE);
        taskMap.put("seqNo", Constants.TASK_SEQ_FOR_INIT);
        List<FollowTask> tsList = taskDao.selectBySchemeVersionid(taskMap);
        if (null == tsList || 0 == tsList.size()) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_SCHEME_TASK_NOT_EXIST, "该方案下无建档任务记录!"));
        }
        FollowTask ftaskVo = tsList.get(0);
        Map<String, Object> taskCntMap = new HashMap<String, Object>();
        taskCntMap.put("schemeVersionid", fsvVo.getId());
        taskCntMap.put("taskId", ftaskVo.getId());
        List<FollowTaskContent> ftcList = taskContentDao.selectByTaskId(taskCntMap);
        if (null == ftcList || 0 == ftcList.size()) {
            return retOutMap;
        }

        List<Object> conDataList = new ArrayList<Object>();
        if (null != ftcList && 0 != ftcList.size()) {
            // questiones
            int chkFlag = 0;
            int ipt = 0;
            int isize = ftcList.size();
            for (ipt = 0; ipt < isize; ipt++) {
                FollowTaskContent ptaskc = ftcList.get(ipt);

                // 获取内容模板
                HashMap<String, Object> contVerMap = new HashMap<String, Object>();
                contVerMap.put("templId", ptaskc.getTemplId());
                contVerMap.put("templVersion", ptaskc.getTemplVersion());
                List<ContentTemplVersion> ctvList = contentTemplDao.selectContentDataByTempl(contVerMap);
                if (null == ctvList || 0 == ctvList.size()) {
                    throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUES_TEMPL_NOT_EXIST, "未查询到任务内容模板记录！");
                }
                ContentTemplVersion ctv = ctvList.get(0);

                String templDataStr = ctv.getTemplData();
                if (StringUtils.isEmpty(templDataStr)) {
                    throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUES_TEMPLDATA_IS_NULL, "任务内容模板内容为空！");
                }

                // 数据库默认配置为json数组格式
                JSONArray templJsonArray = null;
                try {
                    // templJson = JSON.parseObject(templDataStr);
                    templJsonArray = JSON.parseArray(templDataStr);
                    if (2 == chkFlag) {
                        logger.error("多个任务内容模板格式配置不一致，一个配置的是JSONArray，一个是JSONObject！");
                        throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUES_TEMPLDATA_CONFIG_IRREGULAR,
                                "多个任务内容模板格式配置不一致！");
                    }
                    chkFlag = 1;
                    conDataList.add(templJsonArray);
                } catch (JSONException arex) {
                    logger.error("任务内容模板格式配置错误，非json数组格式： " + arex.getMessage());

                    // 非json数组格式，则按json格式再解析
                    JSONObject templJsonObject = null;
                    try {
                        templJsonObject = JSON.parseObject(templDataStr);
                        if (1 == chkFlag) {
                            logger.error("多个任务内容模板格式配置不一致，一个配置的是JSONArray，一个是JSONObject！");
                            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUES_TEMPLDATA_CONFIG_IRREGULAR,
                                    "多个任务内容模板格式配置不一致！");
                        }
                        chkFlag = 2;
                        conDataList.add(templJsonObject);
                    } catch (JSONException exobj) {
                        exobj.printStackTrace();
                        // 后续重写异常类
                        throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUES_TEMPLDATA_CONFIG_IRREGULAR,
                                "问卷模板配置错误，非json格式！"));
                    }
                } catch (AppException appex) {
                    throw (appex);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUES_TEMPLDATA_CONFIG_IRREGULAR,
                            "问卷模板格式解析错误：" + ex.getMessage());
                }
            }
            retOutMap.put("questiones", conDataList);

        }

        return retOutMap;
    }

	@Override
	public List<FollowQueue> getDefaultQueueByDeptId(
			Map<String, Object> paramMap) throws Exception {
		return queueDao.selectDefaultQueueByDeptId(paramMap);
	}
}
